<template>
    <el-card class="item">
        <template #header>
            <div class="card-header">
                <span>气压</span>
            </div>
        </template>
        <div ref="chartContainer" style="width: 100%;height: 250px;"></div>
    </el-card>   
</template>
   
<script setup>   
import { ref, onMounted, watchEffect, onBeforeUnmount } from 'vue';   
import * as echarts from 'echarts';
   
const props = defineProps({
    pressure: Array   
})
   
const chartContainer = ref(null);   
let chartInstance = null;
   
// 初始化图表   
const initChart = () => {
    if (!chartContainer.value) return;
    
    // 销毁旧实例
    if (chartInstance) {
        chartInstance.dispose();
    }
    
    chartInstance = echarts.init(chartContainer.value);
    
    const option = {
        legend: {
            top: "bottom",
        },
        toolbox: {
            show: true,
            feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true },
            },
        },
        series: [{
            name: "气压数据",
            type: "pie",
            radius: [10, 100],
            center: ["50%", "50%"],
            roseType: "area",
            itemStyle: {
                borderRadius: 7,
            },
            // 直接使用props数据
            data: props.pressure,
        }]
    };
    
    chartInstance.setOption(option);   
}
   
// 挂载时初始化   
onMounted(initChart);
   
// 数据变化时更新   
watchEffect(() => {
    if (props.pressure?.length) {
        initChart();
        // 窗口变化时自适应
        window.addEventListener('resize', () => chartInstance?.resize());
    }   
})
   
// 组件卸载时销毁   
onBeforeUnmount(() => {
    chartInstance?.dispose();
    window.removeEventListener('resize', () => chartInstance?.resize());   
})      
</script>   
